<template>
    <div id="content">
        <div id="map" ref="map"></div>
        <h1 id="msg"></h1>
    </div>
</template>

<script>
    import "ol/css";
    import {Map, View, Feature} from "ol";
    import XYZ from "ol/source/XYZ";
    import TileLayer from "ol/layer/Tile";

    import {Vector as VectorSource} from "ol/source";
    import {Vector as VectorLayer, Vector as ShanShuoLayer} from "ol/layer";
    import {Point} from "ol/geom";
    import {circular} from 'ol/geom/Polygon';
    import {Style, Circle as CircleStyle, Fill, Stroke} from "ol/style";
    import {getVectorContext} from "ol/render";

    export default {
        name: "AppCircleSelectFlash",
        data() {
            return {
                map: null,
                circleLayer: null,//圆圈层
                vectorLayer: null,//全局元素层
            };
        },
        methods: {
            drawPoint(site, radius) {
                let features = []
                let circle4326 = circular(site, radius * 1000, 64)
                let circle = circle4326
                console.log('根据坐标点，查询半径范围内的数据点-circle:', circle);

                let feature = new Feature({
                    geometry: circle,
                })
                feature.setStyle(
                    new Style({
                        fill: new Fill({
                            color: 'rgba(32, 157, 230, 1)'
                        }),
                        stroke: new Stroke({
                            color: 'red',
                            lineDash: [10, 10],
                            width: 4,
                        }),
                        image: new CircleStyle({
                            radius: 5,
                            stroke: new Stroke({
                                color: 'red',
                            }),
                            fill: new Fill({
                                color: 'rgba(255, 255, 255, 0.2)',
                            }),
                        }),
                        //
                    })
                )
                features.push(feature)
                let source = new VectorSource()
                source.addFeatures(features)

                this.circleLayer = new VectorLayer({
                    opacity: 0.2
                })
                this.circleLayer.setSource(source)
                this.map.addLayer(this.circleLayer)

                console.log('根据坐标点，查询半径范围内的数据点-circle.getExtent():', circle.getExtent());
                let selectedFeatures = this.vectorLayer.getSource().getFeaturesInExtent(circle.getExtent())

                console.log('根据坐标点，查询半径范围内的数据点-selectedFeatures:', selectedFeatures);
                // 遍历被选中的要素
                var selected = [];
                for (var i = 0; i < selectedFeatures.length; i++) {
                    var selectedFeature = selectedFeatures[i];
                    var name = selectedFeature.get('name');
                    console.log('业务数据信息---', selectedFeature.get('objInfo'))
                    selected.push(name);
                }

                // 输出查询结果
                var msg = selected.join('、');
                document.getElementById('msg').innerText = '被选中的要素：' + msg;

                this.addDynamicPoints(selectedFeatures);
            },

            //添加闪烁效果
            addDynamicPoints(features) {
                let shanshuoLayer = new ShanShuoLayer({source: new VectorSource()});
                // 添加图层
                this.map.addLayer(shanshuoLayer);
                // 循环添加feature
                let pointFeature = [];
                // pointFeature = features
                features.forEach(item => {
                    let point = item.getGeometry()
                    // console.log('选中的元素：', point,point.getCoordinates())

                    const feature = new Feature({
                        geometry: new Point(point.getCoordinates()),
                    });
                    pointFeature.push(feature);
                })
                //把要素集合添加到图层
                shanshuoLayer.getSource().addFeatures(pointFeature);
                // 关键的地方在此：监听postrender事件，在里面重新设置circle的样式
                let radius = 0;
                shanshuoLayer.on("postrender", (evt) => {
                    if (radius >= 30) radius = 0;
                    var opacity = (30 - radius) * (1 / 30); //不透明度
                    var pointStyle = new Style({
                        image: new CircleStyle({
                            radius: radius,
                            stroke: new Stroke({
                                color: "rgba(255,0,0" + opacity + ")",
                                width: 3 - radius / 10, //设置宽度
                            }),
                        }),
                    });
                    // 获取矢量要素上下文
                    let vectorContext = getVectorContext(evt);
                    vectorContext.setStyle(pointStyle);
                    pointFeature.forEach((feature) => {
                        vectorContext.drawGeometry(feature.getGeometry());
                    });
                    radius = radius + 0.3; //调整闪烁速度
                    //请求地图渲染（在下一个动画帧处）
                    this.map.render();
                });
            },


        },
        mounted() {
            // 创建要素图层
            this.vectorLayer = new VectorLayer({
                source: new VectorSource({
                    features: [
                        new Feature({
                            geometry: new Point([120.0, 30.0]),
                            name: 'A',
                            objInfo: 'A-1',
                        }),
                        new Feature({
                            geometry: new Point([120.1, 30.1]),
                            name: 'B',
                            objInfo: 'B-1',
                        }),
                        new Feature({
                            geometry: new Point([120.2, 30.2]),
                            name: 'C',
                            objInfo: 'C-1',
                        })
                    ]
                }),
                style: new Style({
                    image: new CircleStyle({
                        radius: 30,
                        fill: new Fill({
                            color: 'blue'
                        })
                    })
                })
            });

            var gaodeLayer = new TileLayer({
                source: new XYZ({
                    url: "http://webrd0{1-4}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}"
                })
            });
            console.log('map:  ', gaodeLayer)

            // 创建地图
            this.map = new Map({
                target: 'map',
                layers: [
                    gaodeLayer,
                    this.vectorLayer,
                ],
                view: new View({
                    projection: 'EPSG:4326',
                    center: [120, 30],
                    zoom: 10
                })
            });

            let centerPoint = [120.023456, 30.012345]
            let km = 20
            this.drawPoint(centerPoint, km)
        }
    };
</script>
<style lang="scss" scoped>
    #map {
        width: 100%;
        height: 100%;
        position: absolute;
        top: 20px;
        left: 20px;
    }

    /*移除OSM的链接*/
    :deep(.ol-attribution) {
        display: none;
    }
</style>